package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

/**
 * @Description OrderTask
 * @Author zhuzi
 * @Date 2023/10/06
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class OrderTask {

    private final OrderMapper orderMapper;

    /**
     * 定时处理支付超时订单
     * 每分钟处理一次
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processPaymentTimeoutOrders() {
        // 设置参照时间为15min前
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);

        // 获取支付超时的订单
        List<Orders> orders = orderMapper.getOrdersByStatusAndTime(Orders.PENDING_PAYMENT, time);
        if (orders == null || orders.size() == 0) {
            log.info("未发现超时订单-{}", LocalDateTime.now());
            return;
        }

        // 更新订单
        orders.forEach(i -> {
            log.info("处理支付超时订单: {}", i.getId());
            i.setCancelTime(LocalDateTime.now());
            i.setCancelReason("订单支付超时");
            i.setStatus(Orders.CANCELLED);
            orderMapper.updateByOrderId(i);
        });
    }

    /**
     * 定时处理派送中订单
     * 每天凌晨三点处理前一天的派送中订单
     */
    @Scheduled(cron = "0 0 3 * * ?")
    public void processDeliveryOrder() {
        // 设置参照时间为今天的凌晨零点零分零秒
        LocalDateTime time = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);

        // 获取下单时间小于参照时间的订单
        List<Orders> orders = orderMapper.getOrdersByStatusAndTime(Orders.DELIVERY_IN_PROGRESS, time);
        if (orders == null || orders.size() == 0) {
            log.info("未发现派送中订单-{}", LocalDateTime.now());
            return;
        }

        // 更新订单
        orders.forEach(i -> {
            log.info("处理派送中订单: {}", i.getId());
            i.setStatus(Orders.COMPLETED);
            i.setDeliveryTime(LocalDateTime.now());
            orderMapper.updateByOrderId(i);
        });
    }

}
